var express = require('express');
var router = express.Router();
var{Mvs,Users} = require('../utils/model');
var {getDecrypt} = require("../utils/index");
const { MongooseDocument } = require('mongoose');
var monent = require("moment");
const { get } = require('./users');
monent.locale();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//首页路由
router.get('/home', function(req, res, next) {
  res.render('home', { 
    title: '电影评价管理系统' ,
    username:req.session.username,
    logintime:monent(req.session.logintime).format()
  });
});

//登录路由
router.get('/login',function(req,res,next){
  var username = req.query.username ? getDecrypt(req.query.username) : '';
  res.render('login',{title:"登录",username:username})
})

//退出登录路由
router.get("/logout",(req,res)=>{
  req.session.destroy(()=>{
    res.redirect("/home")
  })
})

//注册路由
router.get('/register',function(req,res,next){
  res.render('register',{title:"注册"})
})

//修改密码路由
router.get('/changepass',function(req,res){
    if(req.session.username){
      res.render("changepass",{
        username:req.session.username
      })
    }else{
      res.send("<script>alert('Session已经过期无效,请重新登录');location.href='/login'</script>")
    }
    
})

//列表路由
router.get('/list',function(req,res,next){
  if(req.session.username){
    var query = req.query;
    var keyword = query.keyword;
    var sortObj ={
      _id:1
    }
    var obj = {};
    if(keyword){
      obj={
        $or:[
          {title:new RegExp(keyword)},
          {year:new RegExp(keyword)},
          {genres:new RegExp(keyword)},
          {'rating.average':new RegExp(keyword)},
          {'directors.name':new RegExp(keyword)},
        ]
      }
    }else{
      sortObj = {...query,...sortObj};//对象合并 ...展开运算符
    }
    
    Mvs.find(obj,{_id:0}).sort(sortObj).then(result=>{
      res.render('list',{title:'列表',result,username:req.session.username})
    });
  }else{
    res.send("<script>alert('Session已经过期无效,请重新登录');location.href='/login'</script>")
  }
})

//路由写法
router.get("/findone",(req,res)=>{
  res.json({//可以输出任何东西
    msg:"查询成功",
    code:200,
    url:req.url,
    pathname:req.path,
    query:req.query,  // 查询参数  
    headers:req.headers, // 请求头 
  })
})

module.exports = router;
